﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using BO.Infrastructure.StaticData;
using BO.Infrastructure.Utils;
using Utilities.Entities;

namespace GUI.Controls.News
{
    public partial class ListNews : System.Web.UI.UserControl
    {
        private const int ImageWidthX1 = 200;
        private const int ImageHeightX1 = 150;
        private const int ImageWidthX2 = 300;
        private const int ImageHeightX2 = 225;
        private const int ImageWidthX3 = 660;
        private const int ImageHeightX3 = 320;
        private const int TopRelateNews = 3;

        private const string LiFormat =
            "<li><a href=\"{0}\" title=\"{2}\">" +
            "{1}" +
            "</a></li>";

        private const string ListItemFormat =
            "<li>"
            + "{3}"
            + "<div class=\"scope clearfix\">"
                + "{7}"
                + "<h2><a href=\"{0}\" title=\"{2}\" class=\"prop_title\">{1}{6}</a></h2>"
                + "<p class=\"prop_publishinfo\"><b><span>{4}</span></b></p>"
                + "{5}"
                + "{8}"
            + "</div>"
            + "</li>";

        private const string ListItemFormatForAvatarX3 =
        "<li class=\"x3\">"
            + "<div class=\"scope\">"
                + "<h2><a href=\"{0}\" title=\"{2}\" class=\"prop_title\">"
                + "{1}{4}"
                + "</a></h2>"
            + "</div>"
            + "{3}"
        + "</li>";

        private const string ThreadTitleFormat = "<h3 class=\"prop_thread\"><a href=\"{0}\" title=\"{2}\">{1}</a></h3>";

        private const string RelateNewsFormat = "<ul class=\"relation_news w335 mgt5 fr\">{0}</ul>";

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public bool DataBind(DataTable dt, bool displayDatetime = true)
        {

            if (dt != null && dt.Rows.Count > 0)
            {
                var sb = new System.Text.StringBuilder();

                for (var i = 0; i < dt.Rows.Count; i++)
                {
                    var r = dt.Rows[i];
                    if (DefinedConstants.News.DisplayStyles.AvatarX3.ToString(CultureInfo.InvariantCulture).Equals(r[SqlConstants.NewsPublish.DisplayStyle].ToString()))
                    {

                        sb.Append(GenListItem1(r));
                    }
                    else
                    {
                        int imageWidth, imageHeight;
                        var isAvatarX2 = i % 4 == 0 || DefinedConstants.News.DisplayStyles.AvatarX2.ToString(CultureInfo.InvariantCulture).Equals(r[SqlConstants.NewsPublish.DisplayStyle].ToString());
                        if (isAvatarX2)
                        {
                            imageWidth = ImageWidthX2;
                            imageHeight = ImageHeightX2;
                        }
                        else
                        {
                            imageWidth = ImageWidthX1;
                            imageHeight = ImageHeightX1;
                        }

                        sb.Append(GenListItem(
                            r,
                            dt.Columns.Contains(SqlConstants.Tag.ThreadId) && !string.IsNullOrEmpty(r[SqlConstants.Tag.ThreadId].ToString()) && r[SqlConstants.Tag.ThreadId].ToString() != "0",
                            isAvatarX2,
                            imageWidth,
                            imageHeight,
                            displayDatetime)
                        );

                    }

                }
                ltrData.Text = sb.ToString();
                return true;
            }
            return false;
        }


        /// <summary>
        /// Gen html tin có size ảnh lớn nhất
        /// </summary>
        private static string GenListItem1(DataRow r)
        {

            var avatar = PresentationUtils.Photo.BuildPhoto(
                    r[SqlConstants.NewsPublish.Avatar].ToString(),
                    r[SqlConstants.NewsPublish.Url].ToString(),
                    r[SqlConstants.NewsPublish.Title].ToString(),
                    ImageWidthX3,
                    ImageHeightX3, lazyLoad:true);

            return string.Format(ListItemFormatForAvatarX3,
                r[SqlConstants.NewsPublish.Url],
                r[SqlConstants.NewsPublish.Title],
                r[SqlConstants.NewsPublish.EncodedTitle],
                avatar,
                r[SqlConstants.NewsPublish.NewsTypeIcon]);

        }

        /// <summary>
        /// Gen html tin có size ảnh nhỏ và vừa
        /// </summary>
        private static string GenListItem(DataRow r, bool generateThread, bool genRelateNews, int imageWidth, int imageHeight, bool displayDatetime)
        {

            var avatar = PresentationUtils.Photo.BuildNewsAvatar(r, imageWidth, imageHeight, lazyLoad: true);

            return string.Format(
                ListItemFormat,
                r[SqlConstants.NewsPublish.Url],
                r[SqlConstants.NewsPublish.Title],
                r[SqlConstants.NewsPublish.EncodedTitle],
                avatar,
                !displayDatetime ? string.Empty : PresentationUtils.Object2DateTime(r[SqlConstants.NewsPublish.DistributionDate].ToString()).ToString("dd/MM/yyyy HH:mm"),
                string.IsNullOrEmpty(r[SqlConstants.NewsPublish.InitSapo].ToString())
                    ? string.Empty
                    : string.Format("<p class=\"prop_desc\">{0}</p>", r[SqlConstants.NewsPublish.InitSapo]),
                r[SqlConstants.NewsPublish.NewsTypeIcon],
                generateThread ? GetNewsTag(r) : string.Empty,
                genRelateNews ? GetRelationNews(r[SqlConstants.NewsPublish.NewsRelation].ToString()) : string.Empty
                );




        }

        /// <summary>
        /// Gen link thread nếu tin đc nằm trong dòng sự kiện.
        /// </summary>        
        private static string GetNewsTag(DataRow r)
        {

            return string.Format(
                ThreadTitleFormat,
                PresentationUtils.UrlBuilder.BuildThreadUrl(
                    (int)r[SqlConstants.Tag.ThreadId],
                    r[SqlConstants.Tag.ThreadName].ToString()
                    ),
                r[SqlConstants.Tag.ThreadName],
                PresentationUtils.EnCode(r[SqlConstants.Tag.ThreadName].ToString())
                );
        }

        /// <summary>
        /// Lấy tin liên quan
        /// </summary>
        private static string GetRelationNews(string relationNewsAsJson)
        {
            var relationNews = PresentationUtils.JsonToObject<List<NewsObject>>(relationNewsAsJson);

            if (relationNews != null && relationNews.Count > 0)
            {
                var sb = new System.Text.StringBuilder();
                for (var i = 0; i < Math.Min(TopRelateNews, relationNews.Count); i++)
                {
                    var n = relationNews[i];
                    sb.Append(string.Format(
                        LiFormat,
                        n.Url,
                        n.Title,
                        PresentationUtils.EnCode(n.Title)
                    ));
                }
                return string.Format(RelateNewsFormat, sb);
            }

            return string.Empty;
        }


    }
}